#include "qswiftprogressdialog.h"
#include "ui_qswiftprogressdialog.h"

#include "chronometer.h"

QSwiftProgressDialog::QSwiftProgressDialog(QString title, QString text,
										   int min, int max, QWidget *parent, bool modal) :
	QDialog(parent),
	ui(new Ui::QSwiftProgressDialog)
{
	ui->setupUi(this);

	setWindowTitle(title);
	ui->label->setText(text);
	ui->progressBar->setRange(min, max);
	ui->progressBar->setValue(0);

    startTime = Chronometer::currentTimeMs();
	updateProgressBarText();

	canceled = false;
	setModal(modal);

	show();
}

QSwiftProgressDialog::~QSwiftProgressDialog()
{
	delete ui;
}

void QSwiftProgressDialog::setRange(int min, int max)
{
	ui->progressBar->setRange(min, max);
	updateProgressBarText();
}

QPair<int, int> QSwiftProgressDialog::range()
{
	return QPair<int, int>(ui->progressBar->minimum(), ui->progressBar->maximum());
}

bool QSwiftProgressDialog::wasCanceled()
{
	return canceled;
}

int QSwiftProgressDialog::minimum()
{
	return ui->progressBar->minimum();
}

int QSwiftProgressDialog::maximum()
{
	return ui->progressBar->maximum();
}

void QSwiftProgressDialog::setText(QString text)
{
	ui->label->setText(text);
}

QString QSwiftProgressDialog::text()
{
	return ui->label->text();
}

void QSwiftProgressDialog::setValue(int value)
{
	ui->progressBar->setValue(value);
	updateProgressBarText();
	repaint();
	QApplication::processEvents(QEventLoop::AllEvents, 50);
}

void QSwiftProgressDialog::on_buttonBox_clicked(QAbstractButton *)
{
	canceled = true;
}

void QSwiftProgressDialog::updateProgressBarText()
{
	if (ui->progressBar->value() - ui->progressBar->minimum() > 0) {
        quint64 elapsed = Chronometer::currentTimeMs() - startTime;
		qreal msPerStep = ((qreal)elapsed)/(ui->progressBar->value() - ui->progressBar->minimum());
		quint64 eta = qRound64(msPerStep * (ui->progressBar->maximum() - ui->progressBar->value()));
		ui->progressBar->setFormat(QString("%p% (ETA: %1...)").arg(Chronometer::durationToString(eta, "s")));
	} else {
		ui->progressBar->setFormat(QString("%p% (ETA: calculating...)"));
	}
}
